<template>
  <div class="siteBom">
    <div class="table-page-search-wrapper">
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">
          <p-col :xxl="5" :xl="6">
            <p-form-item label="物料编码">
              <p-input placeholder="请输入内容" v-model="queryParamSelf.mcode"></p-input>
            </p-form-item>
          </p-col>
          <p-col :xxl="5" :xl="6">
            <p-form-item label="物料名称">
              <p-input placeholder="请输入内容" v-model="queryParamSelf.mname"></p-input>
            </p-form-item>
          </p-col>
          <p-col :xxl="5" :xl="6">
            <p-form-item label="物料描述">
              <p-input placeholder="请输入内容" v-model="queryParamSelf.mexplain"></p-input>
            </p-form-item>
          </p-col>

          <p-col :xxl="5" :xl="6">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <p-button type="primary" @click="searchQuerySelf" icon="search">查询</p-button>
              <p-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</p-button>
            </span>
          </p-col>
        </p-row>
      </p-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <p-button @click="handleAddShkill" type="primary" icon="plus">新增</p-button>
       <p-button :disabled="!selectedRowKeys.length > 0" @click="batchDelSkill" style="margin-left: 8px">
          <p-icon type="delete" />删除 
       </p-button>
    </div>
    <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
      <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
      <a style="margin-left: 24px" @click="onClearSelected">清空</a>

      <span style="float:right;">
        <p-divider type="vertical"/>
          <p-popover title="自定义列" trigger="click" placement="leftBottom"  :overlay-style="getWidth">
          <template slot="content">
            <p-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
              <p-row>
                <template v-for="(item,index) in defColumns">
                  <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                      <p-col :span="12"><p-checkbox :value="item.dataIndex">{{ item.title }}</p-checkbox></p-col>
                  </template>
                </template>
              </p-row>
            </p-checkbox-group>
          </template>
          <a><p-icon type="setting" />自定义列</a>
        </p-popover>
      </span>
    </div>
    <p-table
      ref="table"
      size="middle"
      bordered
      rowKey="mcode"
      :columns="columns"
      :data-source="options"
      :pagination="false"
      :scroll="{ y: 390 }"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
      >
        <span slot="action" slot-scope="text, record">
          <p-popconfirm title="确定删除吗?" @confirm="() => handleDeleteSkill(record)">
            <a>删除</a>
          </p-popconfirm>
        </span>
        <span slot="maintenanceKey" slot-scope="text, record">
          {{record.maintenanceKey === 1?'是':'否'}}
        </span>
        <span slot="maintenanceSap" slot-scope="text, record">
           {{maintenanceSapMap[record.maintenanceSap]}}
        </span>
    </p-table>
    <tableChoose 
      @confirm="tableChooseConfirm" 
      tag-name="mname" 
      ref="tableChoose"
      :x="1200"
      :columns="defColumns"/>
  </div>
</template>

<script>
import Vue from 'vue'
import mesPeProcess from "@/api/mesPeProcess";
import tableChoose from './siteBomTableChoose.vue'
// import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import _ from "lodash";
import mixins from './mixins'
export default {
  name: "siteSkill",
  mixins: [mixins],
  // mixins:[JeecgListMixin],
  components: {
    tableChoose,
  },
  props: {
    options: {
      type: Array,
      default: []
    },
    siteIndex: Object,
  },
  data() {
    return {
      selectedRowKeys: [],
      optionsCopy: [],
      selectionRows: null,
      maintenanceSapMap: {
        '1': 'SN管控',
        '2': 'PN管控',
      },
      searchQuery: '',
      queryParamSelf: {
        mcode: '',
        mname: '',
        mexplain: '',
      },
      // 表头
      columns: [
      ],
      //列设置
      settingColumns:[],
      //列定义
      defColumns: [
        /* {
          title: '序号',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align: 'center',
          customRender: function (t,r,index) {
            return parseInt(index)+1;
          }
        }, */
        {
          title: '物料编码',
          align: 'center',
          ellipsis: true,
          dataIndex: 'mcode'
        },
        {
          title: '物料名称',
          align: 'center',
          ellipsis: true,
          dataIndex: 'mname'
        },
        {
          title: '物料描述',
          align: 'center',
          ellipsis: true,
          dataIndex: 'mexplain'
        },
        {
          title: '单位',
          align: 'center',
          ellipsis: true,
          dataIndex: 'unit'
        },
        {
          title: '层级',
          align: 'center',
          ellipsis: true,
          width: 90,
          dataIndex: 'bomLevel'
        },
        {
          title: '替代组',
          align: 'center',
          ellipsis: true,
          width: 90,
          dataIndex: 'bomGroup'
        },
        {
          title: '是否关键物料',
          align: 'center',
          // ellipsis: true,
          scopedSlots: { customRender: 'maintenanceKey' },
          dataIndex: 'maintenanceKey'
        },
        {
          title: 'SAP管控类型',
          align: 'center',
          width: 110,
          // ellipsis: true,
          dataIndex: 'maintenanceSap',
          scopedSlots: { customRender: 'maintenanceSap' },
        },
        {
          title: '总数量',
          align: 'center',
          width: 90,
          // ellipsis: true,
          dataIndex: 'allQuantity'
        },
        {
          title: '可用数量',
          align: 'center',
          width: 90,
          // ellipsis: true,
          dataIndex: 'remainQuantity'
        },
        {
          title: '工站所需数量',
          align: 'center',
          // ellipsis: true,
          dataIndex: 'stationsRequired'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width:110,
          // fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      /* url: {
        list: '/mes-craft/mesPeSkill/list',
      }, */
    };
  },
  watch:{
    options:{
      handler(val){
        console.log(val);
      },
      deep:true,
    }
  },
  computed: {
    baseInfo(){
      return this.$parent.$parent.$refs.BaseInfo.form
    },
    curPens(){
      return this.$parent.canvas.data.pens;
    },
  },
  created() {
    this.initColumns();
    this.optionsCopy = _.cloneDeep(this.options);
  },
  mounted(){
     // 点击物料分配 确定按钮 更新表格数据 直接修改对象引用第一次不生效
    this.evBus.$on('refreshBomData',({drawRoute, curBomData}) =>{
      const curVue = drawRoute.$refs.componentRender;
      curVue.options = curBomData;
      curVue.optionsCopy = _.cloneDeep(curBomData);
    });
  },
  methods: {
    searchQuerySelf(){
      this.options = this.optionsCopy.filter( el =>{
        const mcode = this.queryParamSelf.mcode || el.mcode;
        const mname = this.queryParamSelf.mname || el.mname;
        const mexplain = this.queryParamSelf.mexplain || el.mexplain;
        return (el.mcode || '').includes(mcode) && (el.mname || '').includes(mname) && (el.mexplain || '').includes(mexplain)
      });
    },
    searchReset(){
      this.queryParamSelf.mcode = ''; 
      this.queryParamSelf.mname = ''; 
      this.queryParamSelf.mexplain = '';
      this.options = _.cloneDeep(this.optionsCopy);
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected(){
      this.selectedRowKeys = [];
      this.selectionRows = {}
    },
    tableChooseConfirm(item){
      // 有重复的，已item的为准
      this.options.forEach( (el, index) =>{
        item.forEach( e =>{
          if( el.mcode === e.mcode){
            this.options[index] = _.cloneDeep(e);
          }
        });
      });
      // 并集并去重
      const arr = this.options.concat(item);
      this.options = _.uniqBy(arr,'mcode');
      this.optionsCopy = _.cloneDeep(this.options);
      const {index,pIndex} = this.siteIndex;
      this.$parent.curNode.data.configTree[pIndex].children[index].bomData = this.options;
      this.calcuAndUpdateRemainQuantity();
    },
    handleAddShkill(){
      this.$refs.tableChoose.visible = true;
      this.$refs.tableChoose.selectedRowKeys = this.options.map( el => el.mcode);
    },
    getWidth:function(){
      if(this.defColumns.length > 14){
        return {width : '500px'}
      }
    },
    batchDelSkill(){
      this.$confirm({
        title: '确认删除',
        content: '是否删除选中数据?',
        onOk: () => {
          this.options = this.options.filter( el =>{
            return !this.selectedRowKeys.includes(el.mcode )
          });
          this.selectedRowKeys = [];
          this.optionsCopy = _.cloneDeep(this.options);
          this.calcuAndUpdateRemainQuantity();
        }
      })
    },
    handleDeleteSkill(record){
      const index = this.options.findIndex( el =>el.mcode === record.mcode);
      this.options.splice(index, 1);
      this.optionsCopy = _.cloneDeep(this.options);
      this.calcuAndUpdateRemainQuantity();
    },
    //列设置更改事件
    onColSettingsChange (checkedValues) {
      var key = this.$route.name+":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter(item => {
        if(item.key =='rowIndex'|| item.dataIndex=='action'){
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns =  cols;
    },
    initColumns(){
        // //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        // //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
        // var key = this.$route.name+":colsettings";
        // let colSettings= Vue.ls.get(key);
        // if(colSettings === null || colSettings === undefined){
        //   let allSettingColumns = [];
        //   this.defColumns.forEach(function (item,i,array ) {
        //     allSettingColumns.push(item.dataIndex);
        //   })
        //   this.settingColumns = allSettingColumns;
        //   this.columns = this.defColumns;
        // }else{
        //   this.settingColumns = colSettings;
        //   const cols = this.defColumns.filter(item => {
        //     if(item.key =='rowIndex'|| item.dataIndex=='action'){
        //       return true;
        //     }
        //     if (colSettings.includes(item.dataIndex)) {
        //       return true;
        //     }
        //     return false;
        //   })
        //   this.columns =  cols;
        // }
        this.columns =  this.defColumns;
        this.settingColumns =  this.defColumns.map(function (item) {
          return item.dataIndex;
        });
      }
  },
};
</script>
<style scoped lang='less'>
.siteBom{
}
</style>